package net.st.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.logging.Logger;

import net.st.config.StConfig;

public class DataUtil {

	private static Logger logger = Logger.getLogger(DataUtil.class.getName());

	public static String getEmptyString(String arg0) {
		return arg0 == null ? "" : arg0;
	}

	public static String encryptString(String src) {
		java.security.MessageDigest md5 = null;
		try {
			md5 = java.security.MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			return "";
		}

		String eip;
		byte[] bip;
		String temp = "";
		String tst = src;

		bip = md5.digest(tst.getBytes());
		for (int i = 0; i < bip.length; i++) {
			eip = "" + Integer.toHexString((int) bip[i] & 0x000000ff);
			if (eip.length() < 2)
				eip = "0" + eip;
			temp = temp + eip;
		}
		return temp;
	}

	public static String URLEncode(String lURL) {
		if (DataUtil.isNotNull(lURL)) {
			try {
				return URLEncoder.encode(lURL, "UTF-8");
			} catch (UnsupportedEncodingException e) {
			}
		}

		return "";

	}

	public static boolean isNotNull(String arg0) {
		return arg0 != null && arg0.length() > 0;
	}

	/**
	 * 자동으로 LocalString으로 변경
	 * 
	 * @param val
	 * @return
	 */
	public static String localString(String val) {
		if (val == null)
			return null;
		else {
			byte[] b;

			try {
				b = val.getBytes("8859_1");
				CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
				try {
					decoder.decode(ByteBuffer.wrap(b));
					return val;
				} catch (CharacterCodingException e) {
					logger.info("CharacterCodingException=");
					return new String(b, StConfig.LOCAL_ENCODING);
				}
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
}
